<template>
  <div>
    <el-card shadow="never">
      <div ref="formHeightRef">
        <div style="
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #f1f1f1;
            padding-bottom: 10px;
            align-items: center;
            margin-bottom: 20px;
          ">
          <div style="display: flex; align-items: center">
            <el-checkbox @change="changeFuzzyQuery" v-model="fuzzyQuery">模糊</el-checkbox>
            <el-button type="primary" :icon="Search" @click="getSelectData(formRef)" style="margin-left: 10px">查
              询</el-button>
            <el-button type="primary" :icon="Upload" v-if="configType == 'importDb'"
              @click="importDataBase()">导入</el-button>
          </div>
          <div>
            <el-icon size="20px" v-show="isShowForm">
              <Minus @click="changeFormShow('0')" />
            </el-icon>
            <el-icon size="20px" v-show="!isShowForm">
              <Plus @click="changeFormShow('1')" />
            </el-icon>
          </div>
        </div>
        <!-- <el-divider /> -->
        <div style="margin-bottom: 20px">
          <sc-form v-show="isShowForm" ref="formRef" :config="formConfig" v-model="form" :fileName="fileName">
          </sc-form>
        </div>
        <div style="margin-top: -20px"  ref="buttonHeight">
          <template v-for="(item, index) in toolbars" :key="index">
            <buttonGroup-widget :selectData="selectData" :item="item" @confirmDelClick="confirmDelClick"
              @openDialog="openDialog" @rowAdd="rowAdd"></buttonGroup-widget>
          </template>
          <template v-for="(item, index) in downtoolbars" :key="index">
          <el-dropdown  trigger="click" :type="item.type" split-button>
            {{ item.name }}
            <template #dropdown>
              <el-dropdown-menu>
                <div style="display: flex; flex-direction: column">
                  <template v-for="(item2, index2) in item.children" :key="index2">
                    <buttonGroup-widget :selectData="selectData" commpoentType="dropdownMenu" :item="item2" @confirmDelClick="confirmDelClick"
                      @openDialog="openDialog" @rowAdd="rowAdd"></buttonGroup-widget>
                    </template>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        </div>
      </div>

      <div style="margin-top: 20px; margin-bottom: 80px">
        <div id="table" style="background-color: white; align-content: center">
          <el-table :data="tableData" :height="tableHeight" ref="tableRef" :row-style="rowStyle" v-loading="loading"
            highlight-current-row border :stripe="tableStyle.stripe"
            :header-cell-style="{ color: '#000', 'border-color': '#868686;' }" :lazy="lazy" :load="load" row-key="id"
            :summary-method="getSummaries" :show-summary="showSummary" :tree-props="tableStyle.treeProps"
            @row-click="tableRowChange" @selection-change="selectRow" :key="columnIndex">
            <template v-for="(item, index) in tableConfig" :key="index">
              <tableColunm :item="item" :tableData="tableData" :editKey="editKey" :flexColumnWidth="flexColumnWidth"
                :table-rows="tableRows" @updateTable="getTableData"></tableColunm>
            </template>
            <template #empty>
              <el-empty description="暂无数据" :image-size="100"></el-empty>
            </template>
          </el-table>
          <div v-if="tableMax" style="margin-top: 20px">
            <el-pagination small="true" :total="tableRows" v-model:page-size="pageSize" v-model:current-page="pageNo"
              :page-sizes="tablePage.pageSize" @current-change="pageChange" @size-change="handleSizeChange"
              layout="jumper,sizes,total,prev, pager, next,">
            </el-pagination>
          </div>
        </div>
      </div>
      <div class="dialog"></div>
    </el-card>
    <el-row>
      <div class="table-pagination" ref="pagination">
        <!-- 20 -->
        <div v-if="JSON.stringify(tablePage) !== '{}'">
          <el-pagination small="true" :total="tableRows" v-model:page-size="pageSize" v-model:current-page="pageNo"
            :page-sizes="tablePage.pageSize" @current-change="pageChange" @size-change="handleSizeChange"
            layout="jumper,total,sizes,prev, pager, next">
          </el-pagination>
        </div>
        <div class="pagination-right">
          <el-button @click="tableExport" type="small">
            <i class="iconfont icon-xiazai"></i> 导出
          </el-button>
          <el-tooltip v-if="userLevel === '1'" effect="light" content="查询列表配置" placement="top-end">
            <el-button v-if="userLevel === '1'" :icon="Setting" circle @click="toSetting('/reportSetting')"></el-button>
          </el-tooltip>
          <el-tooltip effect="light" content="表格列设置" placement="top-end">
            <el-button :icon="SetUp" circle @click="dialogVisible = true"></el-button>
          </el-tooltip>
          <div @click="isRefresh(true)" style="margin-left: 10px">
            <el-button :icon="Refresh" circle></el-button>
          </div>
          <div @click="changeTableHeight" style="margin-left: 10px">
            <el-icon size="20px">
              <FullScreen />
            </el-icon>
          </div>
        </div>
      </div>
    </el-row>
    <el-drawer destroy-on-close title="表格列设置" v-model="dialogVisible" size="50%">
      <columnSetting :fileName="fileName" @updateColumn="getInit"></columnSetting>
    </el-drawer>
  </div>
</template>


<script setup>
import {
  ref,
  getCurrentInstance,
  onMounted,
  nextTick,
  render,
  createVNode,
  onUnmounted,
} from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import { ElNotification, ElMessageBox } from "element-plus";
import {
  Plus,
  Delete,
  Edit,
  Reading,
  Minus,
  FullScreen,
  Refresh,
  Search,
  Upload,
  Printer,
  Setting,
  SetUp,
  ArrowUpBold,
  ArrowDownBold,
  ArrowDown
} from "@element-plus/icons-vue";
import { parameterParsing } from "@/utils/parsing";
import Api from "@/api/model/system";
import tsLayer from "@/utils/useDialog";
import "./field-widget/index";
import editColumn from "./column-widget/editColumn.vue";
import tableColunm from "./column.vue";
import columnSetting from "./column-widget/columnSetting.vue";
import buttonGroupWidget from './field-widget/buttonGroup-widget.vue'
import tool from "@/utils/tool";
import screenfull from "screenfull";
const instance = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const formConfig = ref({});
const form = ref({});
const formRef = ref();
const fileName = ref();
// 表格
const columnIndex = ref(0);
const tableType = ref(); //多选单选
const configType = ref();
const tableRef = ref();
const tableConfig = ref();
const tableStyle = ref({});
const tablePage = ref({});
const tableData = ref([]);
const addRecordTemplate = ref({}); //添加行数据模板
const pageNo = ref(1);
const pageSize = ref(20);
const loading = ref(false);
const tableRows = ref(0);
const lazy = ref(false);
//合计
const showSummary = ref(false)
const sumRecord = ref({})
//表格列宽度计算
const flexColumnWidth = ref(true);

const toolbars = ref([]);
const fuzzyQuery = ref(true);//模糊查询
const isShowForm = ref(true);
const formHeightRef = ref();
const buttonHeight = ref();
const pagination = ref();
const paginationHeight = ref();
const dialogVisible = ref(false);

const formHeight = ref();
const tableHeight = ref();
const tableMax = ref(false);
let height = "";
// 单选多选获取行id
const selectData = ref();
//重新渲染edit组件
const editKey = ref();
const userLevel = ref();
const downtoolbars = ref([])
onMounted(() => {
  console.log('mounted')
  var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  if (!iOS) {
    height = window.innerHeight;
  } else {
    height = screen.height;
  }
  let path = route.path.split("/");
  if (path[2] !== undefined) {
    fileName.value = path[2];
  } else if (route.query.fileName) {
    fileName.value = route.query.fileName;
  }
  if (route.query.data !== undefined) {
    form.value = parameterParsing(route.query.data);
  }
  userLevel.value = tool.data.get("USER_INFO").userLevel;
  getInit();
  window.onresize = function () {
    if (!checkFull()) {
      nextTick(() => {
        paginationHeight.value = pagination.value.clientHeight;
        formHeight.value = formHeightRef.value.clientHeight;
        if (formHeight.value) {
          tableHeight.value =
            height * 0.82 - formHeight.value - paginationHeight.value;
        } else {
          tableHeight.value =
            height * 0.77 - paginationHeight.value - buttonHeight.value.clientHeight;
        }
      });
    }
  };
  nextTick(() => {
    paginationHeight.value = pagination.value.clientHeight;
    tableHeight.value = height * 0.6 - paginationHeight.value;
  });
});
onUnmounted(() => {
  window.onresize = null;
});
onBeforeRouteUpdate((to, from) => {
  if (from.isRefresh === true) {
    delete from.isRefresh
    getTableData()
  }
});
//导出数据
const tableExport = async () => {
  var params = {
    fileName: fileName.value,
    fieldMap: form.value,
    fuzzyQuery: fuzzyQuery.value,
  };
  var res = await Api.export.post(params);
  if (res.code == 200) {
    window.open(res.fileName);
  }
};
//设置页面
const toSetting = (val) => {
  router.push({
    path: val,
    query: { fileName: fileName.value },
  });
};
const rowAdd = () => {
  addRecordTemplate.value.show = true;
  tableData.value.unshift(addRecordTemplate.value);
  editKey.value = Date.now();
};
const changeFormShow = (type) => {
  nextTick(() => {
    formHeight.value = formHeightRef.value.clientHeight;
  });
  if (type == 0) {
    isShowForm.value = false;
    tableHeight.value =
      height * 0.77 - paginationHeight.value - buttonHeight.value.clientHeight;
  } else {
    isShowForm.value = true;
    tableHeight.value = height * 0.82 - formHeight.value - paginationHeight.value;
  }
};

/**getInit getTableData用来获取查询列表和表单的配置项以及数据 */
const getInit = async () => {
  dialogVisible.value = false;
  let params = {
    fileName: fileName.value,
  };
  let res = await Api.report.selectCompanyList.post(params);
  if (res.code == 200) {
    formConfig.value = res.bean.form;
    tableConfig.value = res.bean.table.columns; //表格列
    tableType.value = res.bean.table.chooseRows;
    tableStyle.value = res.bean.table;
    configType.value = res.bean.configType;
    lazy.value = res.bean.table.lazy;
    showSummary.value = res.bean.table.showSummary
    flexColumnWidth.value = res.bean.table.flexColumnWidth;
    if (res.bean.table.page !== null) {
      tablePage.value = res.bean.table.page;
    }
    if (res.bean.table.addRecordTemplate !== null) {
      addRecordTemplate.value = res.bean.table.addRecordTemplate;
    }
    if (res.bean.table.page !== null) {
      pageSize.value = res.bean.table.page.page;
    }
    if (res.bean.toolbarGroup !== null) {
      toolbars.value = res.bean.toolbarGroup.toolbars.filter(ele=>{return ele.toolbarType !=='menuButton'});
      downtoolbars.value = res.bean.toolbarGroup.toolbars.filter(ele=>{return ele.toolbarType ==='menuButton'});
    }
    //判断是否初始化显示表格数据
    if (res.initQueryResult == "1") {
      nextTick(() => {
        getTableData();
      });
    }
  }
};
const getTableData = async () => {
  var params = {
    fileName: fileName.value,
    fieldMap: form.value,
    fuzzyQuery: fuzzyQuery.value,
    pageSize: pageSize.value,
    pageNo: pageNo.value, //1
  };
  var res = await Api.select.query.post(params);
  if (res.code == 200) {
    tableConfig.value = res.bean.table.columns;
    showSummary.value = res.bean.table.showSummary
    tableRows.value = res.rows;
    tableData.value = res.reportData;
    console.log(tableData.value)
    if (res.sumRecord) {
      sumRecord.value = res.sumRecord
    }
    editKey.value = Date.now();
  }
  if (!tableMax.value) {
    formHeight.value = formHeightRef.value.clientHeight;
    tableHeight.value = height * 0.82 - formHeight.value - paginationHeight.value;
  }
};
// 提交
const getSelectData = async (formEl) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      getTableData();
    }
  });
};
// 是否模糊查询
const changeFuzzyQuery = (val) => {
  fuzzyQuery.value = val;
};
/**导入数据 */
const importDataBase = async () => {
  let params = {
    fileName: fileName.value,
    fieldMap: form.value,
  };
  let res = await Api.importDataBase.post(params);
  if (res.code == 200) {
    ElNotification.success({ title: "导入成功", message: res.msg });
  }
};
//树形数据的懒加载
const load = async (row, treeNode, resolve) => {
  var params = {
    parentId: row.id,
    fileName: fileName.value,
  };
  var res = await Api.select.query.post(params);
  resolve(res.reportData);
};
//表尾合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合   计'
      return
    }
    for (let key in sumRecord.value) {
      if (key === column.property) {
        sums[index] = sumRecord.value[key]
      }
    }
  })
  return sums
}
//单选获取行数据
const tableRowChange = (row) => {
  if (tableType.value == "1") {
    selectData.value = row;
  }
};
//多选获取行数据
const selectRow = (selection) => {
  selectData.value = selection;
};
// 确认删除
const confirmDelClick = async (url, id) => {
  const res = await Api.systemDelete.post(url, id);
  if (res.code == 200) {
    if (res.optType == "exportFile") {
      window.open(res.data);
    } else {
      ElNotification.success({ title: "", message: "成功！", duration: 2000 });
      getTableData();
    }
  }
};
const pageChange = (val) => {
  pageNo.value = val;
  getTableData();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};
// 刷新
const isRefresh = (val) => {
  if (val) {
    getTableData();
  }
};


// 表格放大
const changeTableHeight = () => {
  tableMax.value = !tableMax.value;
  const element = document.getElementById("table");
  if (screenfull.isEnabled) {
    screenfull.request(element);
    tableHeight.value = height;
  }
};
const checkFull = () => {
  //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
  //火狐浏览器
  var isFull =
    document.mozFullScreen ||
    document.fullScreen ||
    //谷歌浏览器及Webkit内核浏览器
    document.webkitIsFullScreen ||
    document.webkitRequestFullScreen ||
    document.mozRequestFullScreen ||
    document.msFullscreenEnabled;
  if (isFull === undefined) {
    tableMax.value = false;
    isFull = false;
  }
  return isFull;
};
const openDialog = (item, paramsData) => {
  const box = document.querySelector(".dialog");
  render(null, box);
  let path;
  if (paramsData.url !== "" && paramsData.url !== undefined) {
    path = paramsData.url;
  } else {
    path = item.url;
  }
  import(`@/views${path}`).then((res) => {
    const form = createVNode(res.default, {
      paramsData,
      onUpdatetable(val) {
        render(null, box);
        if (val == true) {
          getTableData();
        }
      },
      onOpenDialog(val) {
        openDialog(
          {
            url: "/flowable/processInstance/submitAuditeWorkFlow.vue",
            title: val.title,
            width: "70%",
          },
          val
        );
      },
    });
    tsLayer.open({
      title: item.title || item.name,
      width: item.width,
      fullScreen: item.fullscreen,
      appContext: instance.appContext,
      box: box,
      content: form,
    });
  });
};
</script>


<style lang="scss" scoped>
:deep(.el-table tbody tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.el-table__body tr.current-row > td) {
  background: rgb(223, 240, 217) !important;
}

:deep(.el-table__footer-wrapper) {
  line-height: 23px;
  font-size: 14px;
  font-weight: 600;

}

:deep(.el-table tfoot td.el-table__cell) {
  background-color: rgb(255, 241, 212) !important;
}

.table-pagination {
  width: 100%;
  // width: 90%;
  height: 65px;
  float: right;
  position: fixed;
  bottom: 0px;
  border-top: 1px solid #f1f1f1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 9;
  background: white;
}

// .pagination-container{
//     // float: right;

// }
.pagination-right {
  display: flex;
  align-items: center;
  margin-right: 20%;
}
</style>
